import api from '@/api/request/apiConfig'
import axios from 'axios'
import { isSuccess } from '@/api/request/util'
const CancelToken = axios.CancelToken
export class UploadFile {
  constructor ({ type, apiName, url, formData, config = {} }) {
    this.type = type
    this.path = apiName ? api[apiName] + url : url
    this.formData = formData
    config.timeout = 0
    this.cancel = () => {} // noop
    this.abort = this.abort.bind(this) // 显示的绑定
    const _this = this
    config.cancelToken = new CancelToken(function (c) {
      _this.cancel = c
    })
    this.config = config
  }

  send () {
    return new Promise((resolve, reject) => {
      axios[this.type](this.path, this.formData, this.config).then(res => {
        if (isSuccess(res, this.config)) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      }).catch(err => {
        reject(err)
      })
    })
  }

  abort () {
    this.cancel()
  }
}
